<template>
  <div class="login-container">
    <video
      class="video"
      src="../../assets/video/bg-video-login.mp4"
      loop="loop"
      autoplay="autoplay"
      muted
    ></video>
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <!-- 常规登入 -->
      <h1 class="title">管理系统</h1>
      <i
        @click="isErweiLogin = !isErweiLogin"
        :class="[
          'jiaobiao',
          'iconfont',
          !isErweiLogin ? 'icon-erweimajiaobiao' : 'icon-diannaojiaobiao',
        ]"
      ></i>
      <div class="common-login" v-if="!isErweiLogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            v-model="loginForm.captcha"
            id="captcha_ipt"
            ref="captcha"
            @keydown.native.enter="submitForm('loginForm')"
          ></el-input>
          <span
            class="captchaSvg"
            v-html="captchaSvg"
            @click="updateCaptcha"
          ></span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </div>
      <!-- 二维码登入 -->
      <div class="erwei" v-else-if="isErweiLogin">
        <div class="img">
          <img :src="qrurl" alt="" width="200px" />
          <i class="mask" v-show="isScanCodeSuccess"></i>
        </div>
        <p data-v-cc6c3120="">请用手机微信扫码登录</p>
      </div>
    </el-form>
  </div>
</template>

<script>
var validateCaptcha = (rule, value, callback) => {
  if (value.length !== 5) {
    callback("请注意验证码是五位的！");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  let reg = /^\w{3,12}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback("用户名可以是数字下划线，3-12位");
  }
};
var validatePass = (rule, value, callback) => {
  if (value.length < 3) {
    callback("密码长度不能小于三位");
  } else {
    callback();
  }
};
import * as api from "../../api/index";
import { mapMutations } from "vuex";
import io from "socket.io-client";
import qrcode from "qrcode";
import axios from "axios";
export default {
  data() {
    return {
      captchaSvg: "",
      isScanCodeSuccess: false, // 判断是否扫码成功
      isErweiLogin: false,
      loginForm: {
        // 登入输入框的数据
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      qrurl: "",
    };
  },
  watch: {
    isErweiLogin(newVal, oldVal) {
      //   console.log(newVal);
      if (newVal) {
        // 已经切换成vx扫码
        // 1.通过socket.io和服务器建立连接
        let socket = io("ws://chst.vip");

        // 2.监听socket链接成功 发送请求 请求 "/users/getQrcode" 获取二维码
        socket.on("connectSuccess", (res) => {
          let sid = res.sid;
          // console.log(sid);
          api.getQrcodeUrlApi(sid).then((res) => {
            // console.log(res);
            let qrUrl = res.data.scanCodeUrl;
            qrcode.toDataURL(qrUrl, (err, dataUrl) => {
              // console.log(dataUrl);
              this.qrurl = dataUrl;
            });
          });
        });
        // 3.通过qrcode将二维码地址生成二维码
        // 4.用户扫描二维码
        // 5.监听socket事件scancodeSuccess(此事件不是socket.io定义的，是前后端约定的)
        socket.on("scancodeSuccess", (data) => {
          if (data.state) {
            // 扫码成功
            // 显示遮罩
            this.isScanCodeSuccess = true;
            // 6.发送请求 请求 "/users/wechatLogin" 传递wechatCode
            let wechatCode = data.wechatCode;
            api.wechatLoginApi(wechatCode).then((res) => {
              console.log(res);
              if (res.data.state) {
                // 登入成功
                // 1.将token存储到本地
                localStorage.setItem("qf-token", res.data.token);
                // 2.将userInfo存储到本地
                localStorage.setItem(
                  "qf-userInfo",
                  JSON.stringify(res.data.userInfo)
                );
                // 3.将用户信息添加到vuex
                this.SET_USER_INFO(res.data.userInfo);
                // 4.跳转到首页
                this.$router.push("/");
              } else {
                this.$message.error("微信登入失败");
              }
            });
          } else {
            // 扫码失败
            this.$message.error("扫码失败");
          }
        });
        // 7.判断成功还是失败
      } else {
        // 切换成普通登入  遮罩层消失
        this.isErweiLogin = false;
      }
    },
  },
  created() {
    this.updateCaptcha();
  },
  methods: {
    ...mapMutations(["SET_USER_INFO"]),
    //获取验证码请求的方法
    updateCaptcha() {
      api.getCaptchaApi().then((res) => {
        // console.log(res.data);
        this.captchaSvg = res.data.img;
      });
    },
    submitForm(formName) {
      // 表单验证
      // 1.先校验本地的表单是否通过
      // 2.校验验证码是否正确
      // 3.校验用户名密码是否正确
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 表单验证通过了
          const loading = this.$loading({
            lock: true,
            text: "正在登入",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          // 校验验证码  将用户输入的验证码转成小写
          api
            .verifyCaptcha(this.loginForm.captcha.toLowerCase())
            .then((res) => {
              //   console.log(res);
              if (res.data.state) {
                // console.log(res.data.state);
                // 验证码校验通过
                // 校验用户名和密码
                api
                  .loginApi(this.loginForm.username, this.loginForm.password)
                  .then((res) => {
                    // console.log(res.data);
                    if (res.data.state) {
                      // 登入成功
                      this.$message.success({
                        message: "登入成功,正在跳转...",
                        type: "success",
                        duration: 1000,
                      });
                      // 关闭加载动画
                      loading.close();
                      // 1.将token存储到本地
                      localStorage.setItem("qf-token", res.data.token);
                      // 2.将userInfo存储到本地
                      localStorage.setItem(
                        "qf-userInfo",
                        JSON.stringify(res.data.userInfo)
                      );
                      // 按钮权限
                      localStorage.setItem("permissionButtons",JSON.stringify(res.data.permission.buttons))
                      // 3.将用户信息添加到vuex
                      this.SET_USER_INFO(res.data.userInfo);
                      // 4.跳转到主页
                      this.$router.push("/");
                      // // 测试用
                      // this.$store.dispatch('GET_MENULIST')
                    } else {
                      // 登入不成功
                      //   alert("用户名或者密码输入错误");
                      loading.close();
                      this.$message.error("账号或密码错误");
                    }
                  });
              } else {
                // 校验不通过
                loading.close();
                this.$message.error("验证码错误");
                // 验证码错误清空输入框内已经输入的内容
                this.loginForm.captcha=""
                this.$refs.captcha = focus
                // 验证码错误刷新验证码
                this.updateCaptcha();
              }
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>
<style lang="less" scoped>
.login-container {
  .jiaobiao {
    font-size: 50px;
    color: #fff;
    position: absolute;
    top: -1px;
    right: -1px;
    cursor: pointer;
    opacity: 0.7;
  }
  .video {
    position: fixed;
  }
  .el-form {
    position: fixed;
    left: 65%;
    top: 20%;
    width: 400px;
    background-color: rgba(0, 0, 0, 0.3);
    padding: 80px 26px 66px 0;
    border-radius: 5px;
    /deep/ .el-input__inner {
      width: 250px;
    }
    /deep/ .el-button--primary {
      width: 250px;
      background: linear-gradient(90deg, #1596fb, #002dff);
    }
    /deep/ .el-form-item__label {
      color: #fff;
    }
    .captchaSvg {
      //   background: #fff;
      display: inline-block;
      width: 150px;
      height: 45px;
      text-align: center;
      cursor: pointer;
      border-radius: 0 5px 5px 0;
      margin-left: 10px;
    }
    p {
      text-align: center;
      color: #fff;
      text-indent: 32px;
    }
    .img {
      position: relative;
      width: 200px;
      height: 200px;
      img {
        margin: 0 115px;
        position: absolute;
      }
      i {
        width: 100%;
        height: 100%;
        opacity: 0.8;
        background-color: #fff;
        position: absolute;
        margin: 0 115px;
        background-size: 50%;
        background-repeat: no-repeat;
        background-position: 50%;
        cursor: pointer;
      }
    }
    // /deep/ #captcha_ipt {
    //   border: 0;
    //   border-radius: 5px 0 0 5px;
    //   width: 100px;
    //   height: 45px;
    // }
    // /deep/ .el-form-item__content {
    //   display: flex;
    //   justify-content: flex-start;
    // }
  }
  .title {
    margin: 0 0 40px 0;
    text-align: center;
    color: #fff;
  }
}
</style>